using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Data.SqlClient;
using Example;
using System.Security.Principal;
using System.Threading;
using Example.Business;
using System.Text;
using NBusiness.Data.Validation;
using NBusiness.Data;

namespace www
{
    public partial class Install : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (!Roles.RoleExists("Administrators") ||
                    !Roles.RoleExists("Users") ||
                    !Membership.ValidateUser("admin", "nbusiness!") ||
                    !Membership.ValidateUser("user", "nbusiness!") ||
                    !Roles.IsUserInRole("admin", "Administrators") ||
                    !Roles.IsUserInRole("user", "Users"))
                {
                    ButtonInstallv1000.Enabled = true;
                    InstallRolesLabel.Text = "Install default users and roles.";
                }
            }
        }
        protected void ButtonInstallv1000_Click(object sender, EventArgs e)
        {
            if (!Roles.RoleExists("Administrators")) Roles.CreateRole("Administrators");
            if (!Roles.RoleExists("Users")) Roles.CreateRole("Users");

            MembershipCreateStatus status = MembershipCreateStatus.Success;
            if (!Membership.ValidateUser("admin", "nbusiness!"))
            {
                Membership.CreateUser("admin", "nbusiness!", "admin@example.com", "none", "none", true, out status);
                if (status != MembershipCreateStatus.Success) throw new Exception("Error creating user: " + status.ToString());
            }
            if (!Membership.ValidateUser("user", "nbusiness!"))
            {
                Membership.CreateUser("user", "nbusiness!", "user@example.com", "none", "none", true, out status);
                if (status != MembershipCreateStatus.Success) throw new Exception("Error creating user: " + status.ToString());
            }

            if (!Roles.IsUserInRole("admin", "Administrators")) Roles.AddUserToRole("admin", "Administrators");
            if (!Roles.IsUserInRole("user", "Users")) Roles.AddUserToRole("user", "Users");

            ButtonInstallv1000.Enabled = false;
            InstallRolesLabel.Text = "Installed successfully";
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            DateTime start = DateTime.Now;
            Random r = new Random(DateTime.Now.Millisecond + DateTime.Now.Second + DateTime.Now.Minute);

            CachedBeerStyleCollection styles = CachedBeerStyleCollection.FetchAll();
            CachedRegionCollection regions = CachedRegionCollection.FetchAll();
            CachedAvailabilityCollection availabilites = CachedAvailabilityCollection.FetchAll();

            CompanyCollection companies = CompanyCollection.FetchAll();
            for (int x = 0; x < 100; x++)
            {
                Address a = Address.CreateNew();
                a.City = GenerateRandomString(10, r.Next());
                a.PostalCode = "12345";
                a.Region = regions[r.Next(0, regions.Count - 1)];
                a.Street1 = GenerateRandomString(10, r.Next());
                a.Street2 = GenerateRandomString(10, r.Next());

                Example.Business.Company c = Example.Business.Company.CreateNew();
                c.Addresses.Add(a);
                c.Name = GenerateRandomString(13, r.Next());
                c.Phone = "1234567890";
                c.Url = "http://www.example.com";
                companies.Add(c);

                for (int y = 0; y < 5; y++)
                {
                    Beer b = Beer.CreateNew();
                    b.Alcohol = (decimal?)Convert.ToDecimal(r.NextDouble() / 10);
                    b.Availability = availabilites[r.Next(0, availabilites.Count - 1)];
                    c.Beers.Add(b);
                    b.Name = GenerateRandomString(8, r.Next());
                    b.Style = styles[r.Next(0, styles.Count - 1)];
                }
            }
            //companies.Save();

            KegbotCollection kegbots = KegbotCollection.FetchAll();
            for (int x = 0; x < 10; x++)
            {
                Address a = Address.CreateNew();
                a.City = GenerateRandomString(10, r.Next());
                a.PostalCode = "12345";
                a.Region = regions[r.Next(0, regions.Count - 1)];
                a.Street1 = GenerateRandomString(10, r.Next());
                a.Street2 = GenerateRandomString(10, r.Next());

                Kegbot k = Kegbot.CreateNew();
                k.Address = a;
                k.Image = new byte[r.Next(100, 1000)];
                r.NextBytes(k.Image);
                k.NumLines = r.Next(1, 10);
                k.UserId = Guid.NewGuid();
                kegbots.Add(k);

                for (int y = 0; y < 100; y++)
                {
                    Serving s = Serving.CreateNew();
                    Example.Business.Company c = companies[r.Next(0, companies.Count - 1)];
                    s.Beer = c.Beers[r.Next(0, c.Beers.Count - 1)];
                    string day = r.Next(1, 28).ToString();
                    string month = r.Next(1, 12).ToString();
                    string year = r.Next(1900, 2007).ToString();
                    s.Date = DateTime.Parse(month + "/" + day + "/" + year);
                    s.Kegbot = k;
                    s.Ounces = (decimal)r.Next(1, 16);
                    s.UserId = Guid.NewGuid();
                }
            }
            DateTime end = DateTime.Now;

            DateTime startPersist = DateTime.Now;
            // This will cascade saves through the whole object graph
            companies.Save();
            DateTime endPersist = DateTime.Now;

            int totalRows = 1720;

            Label generateLabel = (Label)LoginView1.FindControl("GenerateLabel");
            generateLabel.Text = string.Format("Generating {0} random entities took {1} seconds.",
                totalRows,
                ((TimeSpan)(end - start)).TotalSeconds);
            generateLabel.Text += string.Format("<BR>Inserting {0} entities took {1} seconds.",
                totalRows,
                ((TimeSpan)(endPersist - startPersist)).TotalSeconds);
            generateLabel.Text += string.Format("<BR>Generation took {0} seconds total.<BR>",
                ((TimeSpan)(endPersist - start)).TotalSeconds);

            Button generateButton = (Button)LoginView1.FindControl("Button1");
            generateButton.Enabled = false;

            HyperLink search = (HyperLink)LoginView1.FindControl("SearchLink");
            search.Visible = true;
        }

        private string GenerateRandomString(int len, int seed)
        {
            Random r = new Random(seed);
            StringBuilder sb = new StringBuilder();
            for (int x = 0; x < len; x++)
            {
                sb.Append((char)r.Next(97, 122));
            }
            return sb.ToString();
        }
    }
}